package com.hw.quartzDemo.demo;

import static java.lang.System.out;

import java.util.ArrayList;
import java.util.List;

import org.quartz.JobBuilder;
import org.quartz.JobDataMap;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SimpleScheduleBuilder;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.impl.StdSchedulerFactory;

import com.hw.quartzDemo.job.HelloJob;

public class DefaultSchedulerDemo {
	public static void doDemo() throws InterruptedException {
out.println( "Quartz demo --------------------------------!" );
        
        Scheduler scheduler;
        List<String> info=new ArrayList<>();
        info.add("电话：17795179212:");
        info.add("住址：宁夏古韵");
        info.add("学校：宁夏大学");
        
		try {
//			1.获取调度器
			scheduler = StdSchedulerFactory.getDefaultScheduler();
			scheduler.start();
			String name=scheduler.getSchedulerName();
			String id=scheduler.getSchedulerInstanceId();
			out.println("schedulerID: "+id+" | schedulerName: "+name+"-------------");
			
//			2.创建工作任务
			/*
			JobDetail设置给job传递的值
			JobDataMap中可以包含不限量的（序列化的）数据对象
			 */
			JobDataMap jobDataMap=new JobDataMap();
			jobDataMap.put("author", "何伟");
			jobDataMap.put("age", 27);
			
			JobDetail jobDetail=JobBuilder.newJob(HelloJob.class)
					.withIdentity("hello_job", "group_1")
					.usingJobData(jobDataMap)
					.build();
			
			
//			3.创建触发器，设定工作出发条件
			/*
			Trigger设置给job传递的值
			 */
			JobDataMap triggerDataMap=new JobDataMap();
			triggerDataMap.put("info", info);
			
			Trigger trigger=TriggerBuilder.newTrigger()
					.withIdentity("hello_trigger", "group_1")
					.startNow()
					.withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(1).repeatForever())
					.usingJobData(triggerDataMap)
					.build();
			
//			4.开始调度任务
			scheduler.scheduleJob(jobDetail, trigger);
			
//			让主线程等待，给Quartz调度给予时间，否则看不到效果
			Thread.sleep(5*1000);
//			在调用scheduler.shutdown()之前，scheduler不会终止，因为还有活跃的线程在执行
			scheduler.shutdown();
		} catch (SchedulerException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
}
